package com.hengjun.baccarat;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hengjun.baccarat.common.ConfigData;
import com.hengjun.baccarat.net.Server;
import com.hengjun.baccarat.net.UrlConn;
import com.hengjun.baccarat.pojo.GlobalService;
import com.hengjun.baccarat.pojo.ViewDataObject;
import com.hengjun.baccarat.utils.BcSysUser;
import com.hengjun.baccarat.utils.DrawForm;
import com.hengjun.baccarat.utils.DrawFourForm;
import com.hengjun.baccarat.utils.DrawThreeForm;
import com.hengjun.baccarat.utils.DrawTwoForm;
import com.hengjun.baccarat.utils.GetJSON;
import com.hengjun.baccarat.utils.RecordCore;
import com.hengjun.baccarat.utils.ThreadManager;

public class OneActivity extends Activity {
	private DrawForm form1;
	private DrawTwoForm form2;
	private DrawThreeForm form3;
	private DrawFourForm form4;

	private HorizontalScrollView scrollView1;
	private HorizontalScrollView scrollView2;
	private HorizontalScrollView scrollView3;
	private HorizontalScrollView scrollView4;

	private ImageButton redButton1;
	private ImageButton redButton2;
	private ImageButton redButton3;
	private ImageButton rendButon4;

	private ImageButton blueButton1;
	private ImageButton blueButton2;
	private ImageButton blueButton3;
	private ImageButton blueButton4;

	private ImageButton greenButton1;
	private ImageButton greenButton2;
	private ImageButton greenButton3;
	private ImageButton greenButton4;

	private Button resetButton;
	private Button xianButton;
	private Button xianduiButton;
	private Button heButton;
	private Button zhuangduiButton;
	private Button zhuangButton;
	private Button clearButton;
	private ImageButton switchButton;

	private boolean show = true;
	private Thread uploadThread;

	private EditText benjinText;
    private TextView number;
	private Button back;

	private AutoUpLoadThead autoUpLoadThead;
	private double totalMoney;
	// 0:單編號 1:記錄主鍵
	private String[] list = new String[] {};
	private String bettingResult = "";
	private Button uploadButton;
	private ProgressDialog dialog;
	private boolean isExitt = false;

	private Button addMoneyButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_one);
		list = this.getIntent().getStringArrayExtra("list");
		Server.SERVER.context = OneActivity.this;
		initView();
		ThreadManager.handler = new testHander();
		autoUpLoadThead = new AutoUpLoadThead();
		autoUpLoadThead.start();
	}
	private double addMoney = 0d;
	private List<RecordCore> rcList = GlobalService.list;

	// 初始化控件
	private void initView() {
		form1 = (DrawForm) findViewById(R.id.form1);
		form2 = (DrawTwoForm) findViewById(R.id.form2);
		form3 = (DrawThreeForm) findViewById(R.id.form3);
		form4 = (DrawFourForm) findViewById(R.id.form4);
		
		scrollView1 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
		scrollView2 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView2);
		scrollView3 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView3);
		scrollView4 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView4);

		scrollView2.setVisibility(View.INVISIBLE);
		scrollView3.setVisibility(View.INVISIBLE);
		scrollView4.setVisibility(View.INVISIBLE);

		benjinText = (EditText) findViewById(R.id.benjinText);
		benjinText.setFocusable(false);
		benjinText.setText(list[2]);

		redButton1 = (ImageButton) findViewById(R.id.imageButton1);
		redButton2 = (ImageButton) findViewById(R.id.imageButton2);
		redButton3 = (ImageButton) findViewById(R.id.imageButton3);
		rendButon4 = (ImageButton) findViewById(R.id.imageButton4);
		redButton1.setOnClickListener(new AllButtonListener());
		redButton2.setOnClickListener(new AllButtonListener());
		redButton3.setOnClickListener(new AllButtonListener());
		rendButon4.setOnClickListener(new AllButtonListener());

		blueButton1 = (ImageButton) findViewById(R.id.blueButton1);
		blueButton2 = (ImageButton) findViewById(R.id.blueButton2);
		blueButton3 = (ImageButton) findViewById(R.id.blueButton3);
		blueButton4 = (ImageButton) findViewById(R.id.blueButton4);
		blueButton1.setOnClickListener(new AllButtonListener());
		blueButton2.setOnClickListener(new AllButtonListener());
		blueButton3.setOnClickListener(new AllButtonListener());
		blueButton4.setOnClickListener(new AllButtonListener());

		greenButton1 = (ImageButton) findViewById(R.id.redButton1);
		greenButton2 = (ImageButton) findViewById(R.id.redButton2);
		greenButton3 = (ImageButton) findViewById(R.id.redButton3);
		greenButton4 = (ImageButton) findViewById(R.id.redButton4);
		greenButton1.setOnClickListener(new AllButtonListener());
		greenButton2.setOnClickListener(new AllButtonListener());
		greenButton3.setOnClickListener(new AllButtonListener());
		greenButton4.setOnClickListener(new AllButtonListener());

		xianButton = (Button) findViewById(R.id.xianButton);
		xianButton.setOnTouchListener(new CleanListener());
		xianduiButton = (Button) findViewById(R.id.xianduiButton);
		xianduiButton.setOnTouchListener(new CleanListener());
		heButton = (Button) findViewById(R.id.heButton);
		heButton.setOnTouchListener(new CleanListener());
		zhuangButton = (Button) findViewById(R.id.zhuangButton);
		zhuangButton.setOnTouchListener(new CleanListener());
		zhuangduiButton = (Button) findViewById(R.id.zhuangduiButton);
		zhuangduiButton.setOnTouchListener(new CleanListener());

		resetButton = (Button) findViewById(R.id.resetButton);

		clearButton = (Button) findViewById(R.id.clearButton);
		resetButton.setOnClickListener(new ResetButtonListener());
		clearButton.setOnClickListener(new AllButtonListener());

		switchButton = (ImageButton) findViewById(R.id.switchButton);
		switchButton.setImageResource(R.drawable.switch_down);
		switchButton.setOnClickListener(new SwitchButtonListener());

		back = (Button) findViewById(R.id.backButton);
		back.setOnClickListener(new AllButtonListener());

		uploadButton = (Button) findViewById(R.id.uploadButton);
		uploadButton.setOnClickListener(new AllButtonListener());

		addMoneyButton = (Button) findViewById(R.id.addMoneyButton);
		addMoneyButton.setOnClickListener(new AddMoneyListener());
		
		number = (TextView) findViewById(R.id.numberRecord);
		number.setText("單編號:" + rcList.get(OrderList.point).getRecordsn());
	}

	private float xPointStart;
	private float yPointStart;

	float xPointEnd;
	float yPointEnd;
	
	public void switchActivity(View v){
		Intent intent = new Intent(OneActivity.this,Activity_Control.class);
		startActivity(intent);
	}

	InputMethodManager inputManager;

	private class AddMoneyListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			final EditText inputAddMoney = new EditText(OneActivity.this);
			inputAddMoney.requestFocus();
			inputAddMoney.setImeOptions(-1);
			inputAddMoney.setInputType(InputType.TYPE_CLASS_NUMBER
					| InputType.TYPE_NUMBER_FLAG_DECIMAL);

			inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.showSoftInput(inputAddMoney,
					InputMethodManager.RESULT_SHOWN);
			inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,
					InputMethodManager.HIDE_IMPLICIT_ONLY);

			AlertDialog.Builder builder = new AlertDialog.Builder(
					OneActivity.this);
			builder.setTitle("請輸入加彩金額")
					.setIcon(R.drawable.new_logo)
					.setView(inputAddMoney)
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
									inputManager.hideSoftInputFromWindow(
											inputAddMoney.getWindowToken(), 0);
								}
							});
			builder.setPositiveButton("確定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							String getRusult = inputAddMoney.getText()
									.toString();
							if (!getRusult.equals("")) {
								double transform = Double
										.parseDouble(getRusult);
								addMoney += Double.parseDouble(GlobalService
										.getDoubleString(transform));

								String benjinTextstr = benjinText.getText()
										.toString();
								if (benjinTextstr.equals("")) {
									benjinTextstr = "0";
								}
								benjinText.setText(GlobalService
										.getDoubleString(Double
												.parseDouble(benjinTextstr)
												+ transform));

							} else {
								AlertDialog.Builder builder1 = new Builder(
										OneActivity.this);
								builder1.setMessage("加彩金額不變!");
								builder1.setTitle("警告").setIcon(
										R.drawable.new_logo);
								builder1.setPositiveButton("返回", null);
								builder1.create().show();
							}
							InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
							inputManager.hideSoftInputFromWindow(
									inputAddMoney.getWindowToken(), 0);
						}
					});
			builder.show();
		}

	}

	private class CleanListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub

			float Height = v.getHeight();
			float Width = v.getWidth();

			switch (event.getAction()) {

			case MotionEvent.ACTION_DOWN:
				xPointStart = event.getX();
				yPointStart = event.getY();
				break;
			case MotionEvent.ACTION_UP:
				xPointEnd = event.getX();
				yPointEnd = event.getY();

				if (xPointEnd - xPointStart > Width / 8
						|| xPointStart - xPointEnd > Width / 8
						|| yPointEnd - yPointStart > Height / 8
						|| yPointStart - yPointEnd > Height / 8) {
					switch (v.getId()) {
					case R.id.zhuangButton:
						zhuangButton.setText("");
						break;
					case R.id.zhuangduiButton:
						zhuangduiButton.setText("");
						break;
					case R.id.heButton:
						heButton.setText("");
						break;
					case R.id.xianduiButton:
						xianduiButton.setText("");
						break;
					case R.id.xianButton:
						xianButton.setText("");
						break;
					}
				} else {
					final Button bu = (Button) v;
					final String str = bu.getText().toString();
					final EditText inputBetting = new EditText(OneActivity.this);
					inputBetting.requestFocus();
					inputBetting.setImeOptions(-1);
					inputBetting.setInputType(InputType.TYPE_CLASS_NUMBER
							| InputType.TYPE_NUMBER_FLAG_DECIMAL);

					inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					inputManager.showSoftInput(inputBetting,
							InputMethodManager.RESULT_SHOWN);
					inputManager.toggleSoftInput(
							InputMethodManager.SHOW_FORCED,
							InputMethodManager.HIDE_IMPLICIT_ONLY);

					AlertDialog.Builder builder = new AlertDialog.Builder(
							OneActivity.this);
					builder.setTitle("請輸入籌碼金額")
							.setIcon(R.drawable.new_logo)
							.setView(inputBetting)
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
											inputManager.hideSoftInputFromWindow(
													inputBetting
															.getWindowToken(),
													0);
										}
									});
					builder.setPositiveButton("確定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									String getRusult = inputBetting.getText()
											.toString();
									if (!getRusult.equals("")) {
										double betting = Double
												.parseDouble(getRusult);
										if (!str.equals("")) {
											double total = betting
													+ Double.parseDouble(str);
											bu.setText(GlobalService
													.getDoubleString(total));
										} else {
											bu.setText(GlobalService
													.getDoubleString(betting));
										}
									} else {
										AlertDialog.Builder builder1 = new Builder(
												OneActivity.this);
										builder1.setMessage("投注金額不變!");
										builder1.setTitle("警告").setIcon(
												R.drawable.new_logo);
										builder1.setPositiveButton("返回", null);
										builder1.create().show();
									}
									InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
									inputManager.hideSoftInputFromWindow(
											inputBetting.getWindowToken(), 0);

								}
							});
					builder.show();
				}
				break;
			}
			return false;
		}

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

//		if (SocketConnection.socket != null
//				&& SocketConnection.socket.isClosed()) {
//			try {
//				new SocketConnection().connecttoserver(BcSysUser.getbcSysUser()
//						.getUserIndex() + "");
//			} catch (IOException e) {
//				e.printStackTrace();
//				handler.obtainMessage(11).sendToTarget();
//			}
//		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
//		try {
//			SocketConnection.socket.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//			handler.obtainMessage(11).sendToTarget();
//		}

	}

	class ResetButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			reset();
		}
	}

	private void reset() {
		addMoney = 0d;
		money = 0;

		xianButton.setText("");
		xianduiButton.setText("");
		zhuangButton.setText("");
		zhuangduiButton.setText("");
		heButton.setText("");

	}

	class SwitchButtonListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (show == true) {
				switchButton.setImageResource(R.drawable.switch_up);
				scrollView1.setVisibility(View.INVISIBLE);
				scrollView3.setVisibility(View.VISIBLE);
				scrollView2.setVisibility(View.VISIBLE);
				scrollView4.setVisibility(View.VISIBLE);
				show = false;
			} else {
				switchButton.setImageResource(R.drawable.switch_down);
				scrollView1.setVisibility(View.VISIBLE);
				scrollView3.setVisibility(View.INVISIBLE);
				scrollView2.setVisibility(View.INVISIBLE);
				scrollView4.setVisibility(View.INVISIBLE);
				show = true;
			}
		}
	}

	class AddButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			final Button bu = (Button) v;
			final String str = bu.getText().toString();
			final EditText inputBetting = new EditText(OneActivity.this);
			inputBetting.setImeOptions(-1);
			inputBetting.setInputType(InputType.TYPE_CLASS_NUMBER
					| InputType.TYPE_NUMBER_FLAG_DECIMAL);
			AlertDialog.Builder builder = new AlertDialog.Builder(
					OneActivity.this);
			builder.setTitle("請輸入籌碼金額").setIcon(R.drawable.new_logo)
					.setView(inputBetting).setNegativeButton("取消", null);
			builder.setPositiveButton("確定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							double betting = Double.parseDouble(inputBetting
									.getText().toString());
							if (!str.equals("")) {
								double total = betting
										+ Double.parseDouble(str);
								bu.setText(GlobalService.getDoubleString(total));
							} else {
								bu.setText(GlobalService
										.getDoubleString(betting));
							}

						}
					});
			builder.show();
		}

	}

	@SuppressWarnings("unused")
	private double money = 0d;

	

	private double culWin(String num) {
		double blankdoubleBenifit = 0d;// 莊對盈利
		double blankBenifit = 0d;// 莊盈利
		double tieBenifit = 0d;// 閑盈利
		double playerBenifit = 0d;// 閑盈利
		double playerDoubleBenifit = 0d;// 閑對盈利

		if (zhuangduiButton.getText().equals(""))
			zhuangduiButton.setText("0");
		if (zhuangButton.getText().equals(""))
			zhuangButton.setText("0");
		if (heButton.getText().equals(""))
			heButton.setText("0");
		if (xianButton.getText().equals(""))
			xianButton.setText("0");
		if (xianduiButton.getText().equals(""))
			xianduiButton.setText("0");

		blankdoubleBenifit = -Double.parseDouble(zhuangduiButton.getText()
				.toString());
		playerDoubleBenifit = -Double.parseDouble(xianduiButton.getText()
				.toString());
		if (num.equals(ConfigData.BANK_DOUBLE_STYLE)
				|| num.equals(ConfigData.BANK_TWO_DOUBLE_STYLE)
				|| num.equals(ConfigData.PLAYERS_BANK_DOUBLE_STYLE)
				|| num.equals(ConfigData.PLAYERS_TWO_DOUBLE_STYLE)
				|| num.equals(ConfigData.TIE_BANK_DOUBLE_STYLE)
				|| num.equals(ConfigData.TIE_TWO_DOUBLE_STYLE)

		) {
			blankdoubleBenifit = Double.parseDouble(zhuangduiButton.getText()
					.toString()) * ConfigData.BANK_DOUBLE_ODDS;
		}
		if (num.equals(ConfigData.BANK_PLAYER_DOUBLE_STYLE)
				|| num.equals(ConfigData.BANK_TWO_DOUBLE_STYLE)
				|| num.equals(ConfigData.PLAYERS_DOUBLE_STYLE)
				|| num.equals(ConfigData.PLAYERS_TWO_DOUBLE_STYLE)
				|| num.equals(ConfigData.TIE_PLAYER_DOUBLE_STYLE)
				|| num.equals(ConfigData.TIE_TWO_DOUBLE_STYLE)

		) {
			playerDoubleBenifit = Double.parseDouble(xianduiButton.getText()
					.toString()) * ConfigData.PLAYER_DOUBLE_ODDS;
		}

		if (!num.equals(ConfigData.TIE_STYLE)
				&& !num.equals(ConfigData.TIE_PLAYER_DOUBLE_STYLE)
				&& !num.equals(ConfigData.TIE_BANK_DOUBLE_STYLE)
				&& !num.equals(ConfigData.TIE_TWO_DOUBLE_STYLE)

		) {

			if (num.equals(ConfigData.BANK_STYLE)
					|| num.equals(ConfigData.BANK_PLAYER_DOUBLE_STYLE)
					|| num.equals(ConfigData.BANK_DOUBLE_STYLE)
					|| num.equals(ConfigData.BANK_TWO_DOUBLE_STYLE)) {

				blankBenifit = Double.parseDouble(zhuangButton.getText()
						.toString()) * ConfigData.BANK_ODDS;

			} else {
				blankBenifit = Double.parseDouble(zhuangButton.getText()
						.toString()) * -1;
			}
			if (num.equals(ConfigData.PLAYERS_STYLE)
					|| num.equals(ConfigData.PLAYERS_BANK_DOUBLE_STYLE)
					|| num.equals(ConfigData.PLAYERS_DOUBLE_STYLE)
					|| num.equals(ConfigData.PLAYERS_TWO_DOUBLE_STYLE)) {

				playerBenifit = Double.parseDouble(xianButton.getText()
						.toString()) * ConfigData.PLAYER_ODDS;

			} else {
				playerBenifit = Double.parseDouble(xianButton.getText()
						.toString()) * -1;
			}

		}
		if (num.equals(ConfigData.TIE_STYLE)
				|| num.equals(ConfigData.TIE_PLAYER_DOUBLE_STYLE)
				|| num.equals(ConfigData.TIE_BANK_DOUBLE_STYLE)
				|| num.equals(ConfigData.TIE_TWO_DOUBLE_STYLE)

		) {
			tieBenifit = Double.parseDouble(heButton.getText().toString())
					* ConfigData.TIEO_DDS;
		} else {
			tieBenifit = Double.parseDouble(heButton.getText().toString()) * -1;
		}
		return blankdoubleBenifit + blankBenifit + tieBenifit + playerBenifit
				+ playerDoubleBenifit;
	}

	class AllButtonListener implements OnClickListener {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			double winTotal = 0d;
			String openType = null;

			switch (arg0.getId()) {
			case R.id.imageButton1:
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.BANK_STYLE_NAME));
				openType = ConfigData.BANK_STYLE;
				GlobalService.culBigStreetCellObject(
						ConfigData.BANK_STYLE_NAME, winTotal);
				break;
			case R.id.imageButton2:
				openType = ConfigData.BANK_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.BANK_DOUBLE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.BANK_DOUBLE_STYLE_NAME, winTotal);
				break;
			case R.id.imageButton3:
				openType = ConfigData.BANK_PLAYER_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.BANK_PLAYER_DOUBLE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.BANK_PLAYER_DOUBLE_STYLE_NAME, winTotal);
				break;
			case R.id.imageButton4:
				openType = ConfigData.BANK_TWO_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.BANK_TWO_DOUBLE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.BANK_TWO_DOUBLE_STYLE_NAME, winTotal);
				break;
			case R.id.blueButton1:
				openType = ConfigData.PLAYERS_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.PLAYERS_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.PLAYERS_STYLE_NAME, winTotal);
				break;
			case R.id.blueButton2:
				openType = ConfigData.PLAYERS_BANK_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.PLAYERS_BANK_DOUBLE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.PLAYERS_BANK_DOUBLE_STYLE_NAME, winTotal);
				break;
			case R.id.blueButton3:
				openType = ConfigData.PLAYERS_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.PLAYERS_DOUBLE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.PLAYERS_DOUBLE_STYLE_NAME, winTotal);
				break;
			case R.id.blueButton4:
				openType = ConfigData.PLAYERS_TWO_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.PLAYERS_TOW_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.PLAYERS_TOW_STYLE_NAME, winTotal);
				break;
			case R.id.redButton1:
				openType = ConfigData.TIE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.TIE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(ConfigData.TIE_STYLE_NAME,
						winTotal);
				break;
			case R.id.redButton2:
				openType = ConfigData.TIE_BANK_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.TIE_BANK_DOUBLE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.TIE_BANK_DOUBLE_STYLE_NAME, winTotal);
				break;
			case R.id.redButton3:
				openType = ConfigData.TIE_PLAYER_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.TIE_PLAYER_DOUBLE_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.TIE_PLAYER_DOUBLE_STYLE_NAME, winTotal);
				break;
			case R.id.redButton4:
				openType = ConfigData.TIE_TWO_DOUBLE_STYLE;
				winTotal = culWin(GlobalService
						.getOpenType(ConfigData.TIE_TOW_STYLE_NAME));
				GlobalService.culBigStreetCellObject(
						ConfigData.TIE_TOW_STYLE_NAME, winTotal);
				break;
			// 撤銷按鈕
			case R.id.backButton:
				autoUpLoadThead.setCode("-1");
				uploadThread = new Thread(run2);
				uploadThread.start();

				return;
				// 上傳按鈕
			case R.id.uploadButton:
				try {
					autoUpLoadThead.setCode("-1");
				} catch (Exception e) {
					e.printStackTrace();
				}
				uploadThread = new Thread(run);
				uploadThread.start();

				return;
				// 重開按钮
			case R.id.clearButton:
				AlertDialog.Builder builder = new Builder(OneActivity.this);
				builder.setMessage("確定重開?");
				builder.setTitle("提示").setIcon(R.drawable.new_logo);
				builder.setPositiveButton("確定",
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								

								uploadThread = new Thread(resetRun);
								uploadThread.start();

								
							}
						});
				builder.setNegativeButton("取消",
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						});
				builder.create().show();
				return;
			}

			handler.obtainMessage(5).sendToTarget();
			totalMoney = winTotal
					+ Double.parseDouble(benjinText.getText().toString()
							.equals("") ? "0" : benjinText.getText().toString());
			bettingResult = "{\"match\":" + GlobalService.totalMatch()
					+ ",\"yaZd\":" + zhuangduiButton.getText().toString()
					+ ",\"yaZ\":" + zhuangButton.getText().toString()
					+ ",\"yaH\":" + heButton.getText().toString() + ",\"yaX\":"
					+ xianButton.getText().toString() + ",\"yaXd\":"
					+ xianduiButton.getText().toString() + ",\"result\":\""
					+ openType + "\",\"resultWin\":" + winTotal + ",\"total\":"
					+ totalMoney + ",\"bacCartSysuerIndex\":"
					+ BcSysUser.getbcSysUser().getUserIndex()
					+ ",\"recordindex\":" + list[1] + ",\"addMoney\":"
					+ addMoney + "}";
//			bettingResult =  GlobalService.totalMatch()
//					+ "," + zhuangduiButton.getText().toString()
//					+ "," + zhuangButton.getText().toString()
//					+ "," + heButton.getText().toString() + ","
//					+ xianButton.getText().toString() + ","
//					+ xianduiButton.getText().toString() + ","
//					+ openType + "," + winTotal + ","
//					+ totalMoney + ","
//					+ BcSysUser.getbcSysUser().getUserIndex()
//					+ "," + list[1] + ","
//					+ addMoney ;
			benjinText.setText(GlobalService.getDoubleString(totalMoney));
			GlobalService.addBettingResultList(bettingResult);
			reset();
		}

	}

	double backMoney = 0d;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			if (msg.what == 0) {
				AlertDialog.Builder builder = new Builder(OneActivity.this);
				builder.setMessage("不能操作該單號!");
				builder.setTitle("退出提示").setIcon(R.drawable.new_logo);
				;
				builder.setPositiveButton("確定",
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Intent _intent = new Intent(OneActivity.this,
										OrderList.class);
								OneActivity.this.startActivity(_intent);
								OneActivity.this.finish();
							}
						});
				builder.create().show();
			}
			if (msg.what == 1) {
				try {
					dialog = ProgressDialog.show(OneActivity.this, "網絡提示",
							"正在上傳數據,請稍後！");
					dialog.setIcon(R.drawable.new_logo);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			if (msg.what == 2) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			if (msg.what == 3) {
				AlertDialog.Builder builder = new Builder(OneActivity.this);
				builder.setMessage("網絡故障,上傳失敗!");
				builder.setTitle("退出提示").setIcon(R.drawable.new_logo);
				builder.setPositiveButton("退出",
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								OneActivity.this.finish();
							}
						});
				builder.create().show();
			}

			if (msg.what == 4) {
				dialog = ProgressDialog.show(OneActivity.this, "網絡提示",
						"正在撤銷,請稍後！");
				dialog.setIcon(R.drawable.new_logo);
			}
			if (msg.what == 5) {
				form1.invalidate();
				form2.invalidate();
				form3.invalidate();
				form4.invalidate();
			}
			if (msg.what == 6) {
				autoUpLoadThead.interrupt();
				OneActivity.this.finish();
			}
			if (msg.what == 7) {
				clearButton.setEnabled(false);
				back.setEnabled(false);
				uploadButton.setEnabled(false);
				checkAuto = false;
			}
			if (msg.what == 8) {
				clearButton.setEnabled(true);
				back.setEnabled(true);
				uploadButton.setEnabled(true);
				checkAuto = true;
			}
			if (msg.what == 9) {
				AlertDialog.Builder builder = new Builder(OneActivity.this);
				builder.setMessage("数据上传中!");
				builder.setTitle("返回提示").setIcon(R.drawable.new_logo);
				builder.setPositiveButton("返回", null);
				builder.create().show();
			}
			if (msg.what == 10) {
				if (backMoney != 0) {
					String benjinstr = benjinText.getText().toString();
					double captial =Double.parseDouble(benjinstr)   -backMoney;
					benjinText.setText(GlobalService.getDoubleString(captial));
				}
				backMoney = 0;
			}
			if (msg.what == 11) {
				AlertDialog.Builder builder = new Builder(OneActivity.this);
				builder.setMessage("網絡連接異常!");
				builder.setTitle("返回提示").setIcon(R.drawable.new_logo);
				builder.setPositiveButton("返回", null);
				builder.create().show();
			}
			if(msg.what == 12){
				form1.invalidate();
				form2.invalidate();
				form3.invalidate();
				form4.invalidate();

				money = 0;
				xianButton.setText("");
				xianduiButton.setText("");
				zhuangButton.setText("");
				zhuangduiButton.setText("");
				heButton.setText("");
				
				clearButton.setEnabled(true);
				back.setEnabled(true);
				uploadButton.setEnabled(true);
				checkAuto = true;
			}
		}
	};

	private Runnable run2 = new Runnable() {
		@Override
		public void run() {
			String result;
			try {
				result = UrlConn.queryPort(list[1]);
				if (ViewDataObject.getViewDataObject().getBigStreetArrayList()
						.size() != 0) {
					if (result != null && !result.equals("-1")) {
						
						double temobackMoney = UrlConn.getBackMoney();
						List<String> bettingList = ViewDataObject
								.getViewDataObject().getBettingResultList();
						if (bettingList.size() > 0) {

							String[] str = bettingList.get(
									bettingList.size() - 1).split(",");
							String[] backString = str[7].split(":");
							String[] backAddMOneyString = str[11].split(":");
							String backStr = backString[backString.length - 1];
							String backStrAddMoney = backAddMOneyString[backAddMOneyString.length - 1].replaceAll("[}]","");
							backMoney = Double.parseDouble(backStr)+Double.parseDouble(backStrAddMoney);
						} else {
							backMoney = temobackMoney;
						}
						handler.obtainMessage(10).sendToTarget();
						GlobalService.back();
						try {
							List<Object> bigStreet = ViewDataObject.getViewDataObject().getBigStreetArrayList();
							String bigStreetStr=  GetJSON.getListJson(bigStreet);
							if(bigStreetStr.equals("")){
								handler.obtainMessage(4).sendToTarget();
							GlobalService.upLoad(list[1], "backNull");
							UrlConn.ListQuery(list[1] + "");
							handler.obtainMessage(2).sendToTarget();
							}
							
						} catch (Exception e) {
							e.printStackTrace();
							handler.obtainMessage(2).sendToTarget();
							handler.obtainMessage(3).sendToTarget();
						}
					} else {
						try {
							GlobalService.list = UrlConn.RecordConn();
							handler.obtainMessage(0).sendToTarget();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							handler.obtainMessage(3).sendToTarget();
						}
					}
				} else {
					if (result != null && !result.equals("-1")) {
						handler.obtainMessage(4).sendToTarget();
						try {
							GlobalService.upLoad(list[1], "null");
							UrlConn.ListQuery(list[1] + "");
							handler.obtainMessage(2).sendToTarget();
						} catch (Exception e) {
							handler.obtainMessage(2).sendToTarget();
							e.printStackTrace();
							handler.obtainMessage(3).sendToTarget();
						}
					} else {
						try {
							GlobalService.list = UrlConn.RecordConn();
							handler.obtainMessage(0).sendToTarget();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							handler.obtainMessage(3).sendToTarget();
						}
					}
				}
				autoUpLoadThead.setCode("-1");
				handler.obtainMessage(5).sendToTarget();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				handler.obtainMessage(11).sendToTarget();
			}

		}
	};

	class AutoUpLoadThead extends Thread {
		boolean flag = false;
		private String code = "";

		@Override
		public void run() {
			while (true) {
				try {
					String code = getCode();
					if (code.equals("")) {
						Thread.sleep(60000*3);
						handler.obtainMessage(7).sendToTarget();
						uploadData();
						handler.obtainMessage(8).sendToTarget();
					}
				} catch (Exception e) {
					e.printStackTrace();
					handler.obtainMessage(8).sendToTarget();
					break;
				}
			}
		}

		public synchronized String getCode() {
			while (flag) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
					Toast.makeText(OneActivity.this, "程序發生錯誤退出", Toast.LENGTH_SHORT).show();
				}
			}
			return code;
		}

		public synchronized void setCode(String code) {

			if (code.equals("")) {
				flag = false;
				this.notify();
				this.code = code;
			} else {
				flag = true;
			}

		}

	}

	private Runnable resetRun = new Runnable() {

		@Override
		public void run() {
			
//			handler.obtainMessage(7).sendToTarget();
//			handler.obtainMessage(8).sendToTarget();
			// TODO Auto-generated method stub
//			handler.obtainMessage(1).sendToTarget();
			handler.obtainMessage(7).sendToTarget();
			try {
				uploadData();
				ViewDataObject.resetViewData();
				autoUpLoadThead.setCode("-1");
				uploadData();
//				handler.obtainMessage(2).sendToTarget();
				handler.obtainMessage(12).sendToTarget();
			} catch (Exception e) {
//				handler.obtainMessage(2).sendToTarget();
				handler.obtainMessage(12).sendToTarget();
				handler.obtainMessage(3).sendToTarget();
				e.printStackTrace();
			}
			autoUpLoadThead.setCode("");
			if (isExitt) {
				handler.obtainMessage(6).sendToTarget();
			}
		}

	};
	
	private Runnable run = new Runnable() {

		@Override
		public void run() {
			
//			handler.obtainMessage(7).sendToTarget();
//			handler.obtainMessage(8).sendToTarget();
			// TODO Auto-generated method stub
//			handler.obtainMessage(1).sendToTarget();
			handler.obtainMessage(7).sendToTarget();
			try {
				uploadData();
//				handler.obtainMessage(2).sendToTarget();
				handler.obtainMessage(8).sendToTarget();
			} catch (Exception e) {
//				handler.obtainMessage(2).sendToTarget();
				handler.obtainMessage(8).sendToTarget();
				handler.obtainMessage(3).sendToTarget();
				e.printStackTrace();
			}
			autoUpLoadThead.setCode("");
			if (isExitt) {
				handler.obtainMessage(6).sendToTarget();
			}
		}

	};

	private synchronized void uploadData(){
		try {
			String result = UrlConn.queryPort(list[1]);
			if (result != null && !result.equals("-1")) {
				GlobalService.upLoad(list[1], bettingResult);

			} else {
				GlobalService.list = UrlConn.RecordConn();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			handler.obtainMessage(11).sendToTarget();
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.one, menu);
		return true;
	}

	@SuppressLint("HandlerLeak")
	class testHander extends Handler {
		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 0) {
				AlertDialog.Builder builder = new Builder(OneActivity.this);
				builder.setMessage("賬戶異地登陸!");
				builder.setTitle("退出提示").setIcon(R.drawable.new_logo);
				builder.setPositiveButton("確定",
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Intent _intent = new Intent(OneActivity.this,
										Login.class);
								OneActivity.this.startActivity(_intent);
								OneActivity.this.finish();
							}
						});

				builder.create().show();
			}
		}
	}

	private boolean checkAuto = true;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent eve ) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (checkAuto) {
				try {
					isExitt = true;
					uploadThread = new Thread(run);
					uploadThread.start();

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(OneActivity.this, "程序發生錯誤退出!", Toast.LENGTH_SHORT).show();
				}
				return true;
			} else {
				handler.obtainMessage(9).sendToTarget();
			}
		}
		return false;
	}
}
